package org.web.ssm.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web.ssm.dao.ShoppingMapper;
import org.web.ssm.dto.Shoppinglist;
import org.web.ssm.exception.BaseException;
import org.web.ssm.exception.ShoppingException;
import org.web.ssm.model.Shopping;
import org.web.ssm.service.wechatService.IShoppingService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LUOLIANG on 2016/6/18.
 */
@Service
public class ShoppingServiceImpl implements IShoppingService {
    private Logger logger = LogManager.getLogger(ShoppingServiceImpl.class);
    @Autowired
    private ShoppingMapper shoppingMapper;

    @Override
    public Shoppinglist getListBytype(String userid) {
        List<Shopping> allList = shoppingMapper.selectAll(userid);
        List<Shopping> finishlist = new ArrayList<Shopping>();
        List<Shopping> todolist = new ArrayList<Shopping>();

        for (int i = 0; i < allList.size(); i++) {
            Shopping shopping = allList.get(i);
            if (shopping.isfinish()) {
                finishlist.add(shopping);
            } else {
                todolist.add(shopping);
            }
        }

        Shoppinglist shoppinglist = new Shoppinglist(finishlist, todolist);

        return shoppinglist;
    }

    @Override
    public void insertShopping(Shopping shopping) {
        try {
            int res = shoppingMapper.insertShopping(shopping);
            if (res != 1) {
                throw new ShoppingException("插入失败");
            }
        } catch (ShoppingException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BaseException("插入操作异常：" + e.getMessage());
        }
    }

    @Override
    public void updateShopping(String id) {
        try {
            Shopping shopping = shoppingMapper.selectByPrimaryKey(id);
            shopping.setIsfinish(true);
            int res = shoppingMapper.updateShopping(shopping);
            if (res != 1) {
                throw new ShoppingException("更新失败");
            }
        } catch (ShoppingException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BaseException("更新操作异常：" + e.getMessage());
        }
    }

    @Override
    public void deleteShoppping(String id) {
        try {
            int res = shoppingMapper.deleteShopping(id);
            if (res != 1) {
                throw new ShoppingException("删除失败");
            }
        } catch (ShoppingException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BaseException("删除操作异常：" + e.getMessage());
        }
    }
}
